package com.hair.grpc.example.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import io.grpc.CallOptions;
import io.grpc.Channel;
import io.grpc.ClientCall;
import io.grpc.ClientInterceptor;
import io.grpc.ForwardingClientCall.SimpleForwardingClientCall;
import io.grpc.ForwardingClientCallListener.SimpleForwardingClientCallListener;
import io.grpc.Metadata;
import io.grpc.MethodDescriptor;
import io.grpc.Status;

public class HeaderClientInterceptor implements ClientInterceptor {

    private final Logger logger = LoggerFactory.getLogger(HeaderClientInterceptor.class);

    private static final Metadata.Key<String> CLIENT_ID = Metadata.Key.of("client_id", Metadata.ASCII_STRING_MARSHALLER);

    private String clientId;

    public HeaderClientInterceptor(String clientId) {
        this.clientId = clientId;
    }

    @Override
    public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {

        return new SimpleForwardingClientCall<ReqT, RespT>(next.newCall(method, callOptions)) {

            @Override
            public void start(Listener<RespT> responseListener, Metadata headers) {
                headers.put(CLIENT_ID, clientId);
                super.start(new SimpleForwardingClientCallListener<RespT>(responseListener) {

                    /**
                     * {@inheritDoc}
                     * @see io.grpc.ForwardingClientCallListener#onClose(Status, Metadata)
                     */
                    @Override
                    public void onClose(Status status, Metadata trailers) {
                        super.onClose(status, trailers);
                    }

                    @Override
                    public void onHeaders(Metadata headers) {
                        logger.debug("获取请求返回头部信息,{}", headers.toString());
                        super.onHeaders(headers);
                    }

                }, headers);
            }

        };

    }

}
